package com.xj.thread;

import com.xj.thrift.client.AdditionService;
import com.xj.thrift.client.ClientDemo;
import com.xj.util.ExceptionUtil;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author: xiajun
 * Date: 2014-07-16
 * Time: 10:00:00
 * 验证线程池中，执行线程任务超时的时候
 * 将线程中断，看该中断线程是否还会被使用
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        //Executors.newFixedThreadPool(10);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100), new DemoFactory());
        final Thread[] t = new Thread[1];
        Future f1 = pool.submit(new Runnable() {
            @Override
            public void run() {
                t[0] = Thread.currentThread();
                try {
                    int i=System.in.read();
                    System.out.println("----"+i);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                /*try {
                    AdditionService.Client s=ClientDemo.getNioClient();
                    int s2=s.add(1,5);
                    System.out.println(s2);
                } catch (TTransportException e) {
                    e.printStackTrace();
                } catch (TException e) {
                    e.printStackTrace();
                }*/
            }
        });
        try {
            f1.get(2, TimeUnit.SECONDS);
        } catch (Exception e) {
            System.out.println(ExceptionUtil.getSimpleInfo(e));
            t[0].interrupt();
            System.out.println(t[0].isInterrupted());
        }
        System.out.println("-----------------------------------------");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 6; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "......");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println(">>>>>>>>>" + ExceptionUtil.getSimpleInfo(e));
                    }
                }
            });
        }
    }
}

class DemoFactory implements ThreadFactory {
    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setName("Demo-thread-pool-" + count.incrementAndGet());
        return thread;
    }
}
